package com.vates.login.dao.impl;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.vates.login.dao.GenericDAO;

/**
 * This class serves as the Base class for all other DAOs - namely to hold
 * common CRUD methods that they might all use. You should only need to extend
 * this class when your require custom CRUD logic.
 *
 * @param <T> a type variable
 * @param <PK> the primary key for that type
 */
public abstract class GenericDaoHibernate<T extends Serializable, PK extends Serializable> implements GenericDAO<T, PK> {

	private Class<T> persistentClass;
	@Autowired
	protected HibernateTemplate hibernateTemplate;

	
    /**
     * Constructor that takes in a class to see which type of entity to persist.
     * Use this constructor when subclassing.
     *
     * @param persistentClass the class type you'd like to persist
     */
    public GenericDaoHibernate(final Class<T> persistentClass) {
        this.persistentClass = persistentClass;
    }
    
    @Override
    public List<T> getAll() {
        return hibernateTemplate.loadAll(this.persistentClass);
    }

    @Override
	public T get(PK id) {
        T entity = (T) hibernateTemplate.get(this.persistentClass, id);
        return entity;
    }

    @Override
	public boolean exists(PK id) {
        T entity = (T) hibernateTemplate.get(this.persistentClass, id);
        return entity != null;
    }

	@SuppressWarnings("unchecked")
    @Override
	public PK save(T object) {
        return (PK) hibernateTemplate.save(object);
    }

    @Override
     public void delete(PK id) {
    	 hibernateTemplate.delete(this.get(id));
    }

   @SuppressWarnings("unchecked")
   @Override
   public List<T> findByNamedQuery(String queryName, Map<String, Object> queryParams) {
        String[] params = new String[queryParams.size()];
        Object[] values = new Object[queryParams.size()];
        
        int index = 0;
        for (String s : queryParams.keySet()) {
            params[index] = s;
            values[index++] = queryParams.get(s);
        }

        return hibernateTemplate.findByNamedQueryAndNamedParam(queryName, params, values);
    }
}
